package com.ll.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ll.utils.DateUtil;
import com.ll.utils.StringUtil;
import com.ll.utils.TimeZoneUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ll.config.EmailServerConfiguration;
import com.ll.dao.entity.EmailMessage;
import com.ll.dao.mapper.EmailMessageMapper;
import com.ll.dao.mapper.EmailMessageMapperExt;
import com.ll.exception.UserException;
import com.ll.exception.UserExceptionConstants;
import com.ll.sender.TaskQueue;
import com.ll.service.EmailMessageService;
import com.ll.service.EmailServerService;
import com.ll.vo.request.EmailMessageRequestVo;
import com.ll.vo.response.EmailMessageResponseVo;
import com.ll.vo.response.EmailServerResponseVo;
import com.ll.vo.response.PrimaryIdVo;

@Service
public class EmailMessageServiceImpl implements EmailMessageService {

	private static final Logger LOGGER = LoggerFactory.getLogger(EmailMessageServiceImpl.class);
	private EmailServerConfiguration emailServerConfiguration = new EmailServerConfiguration();

	@Autowired
	private EmailMessageMapper emailMessageMapper;
	@Autowired
	private EmailMessageMapperExt emailMessageMapperExt;
	@Autowired
	private EmailServerService emailServerService;

	/**
	 * 发送邮件
	 * 
	 * @param emailMessageRequestVo
	 * @return
	 */
	@Override
	public PrimaryIdVo sendEmailMessage(EmailMessageRequestVo emailMessageRequestVo) {
		EmailMessage emailMessage = new EmailMessage();
		String id = StringUtil.createUUID();
		try {
			DateConverter dateConverter = new DateConverter();
			dateConverter.setTimeZone(TimeZoneUtil.getDefaultTimeZone());
			dateConverter.setPatterns(new String[] { "yyyy-MM-dd" });
			ConvertUtils.register(dateConverter, Date.class);
			BeanUtils.copyProperties(emailMessage, emailMessageRequestVo);
			String locked = StringUtil.createUUID();
			emailMessage.setLocked(locked);
			emailMessage.setLockedTime(new Date());

			emailMessage.setFireTimes(0);
			emailMessage.setLastFireOn(new Date());

		} catch (IllegalAccessException e) {
			LOGGER.error("EmailMessageRequestVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		} catch (InvocationTargetException e) {
			LOGGER.error("EmailMessageRequestVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
		try {
			emailMessage.setId(id);
			emailMessageMapper.insertEmailMessage(emailMessage);
		} catch (Exception e) {
			LOGGER.error("新增邮件信息时报错", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
		EmailMessageResponseVo emailMessageResponseVo = new EmailMessageResponseVo();
		try {
			DateConverter dateConverter = new DateConverter();
			dateConverter.setTimeZone(TimeZoneUtil.getDefaultTimeZone());
			dateConverter.setPatterns(new String[] { "yyyy-MM-dd" });
			ConvertUtils.register(dateConverter, Date.class);
			BeanUtils.copyProperties(emailMessageResponseVo, emailMessage);
			if(StringUtils.isNotBlank(emailMessageResponseVo.getLockedTime())){
				emailMessageResponseVo.setLockedTime(DateUtil.date2String(emailMessage.getLockedTime(), "yyyy-MM-dd"));
			}
			if(StringUtils.isNotBlank(emailMessageResponseVo.getLastFireOn())){
				emailMessageResponseVo.setLastFireOn(DateUtil.date2String(emailMessage.getLastFireOn(), "yyyy-MM-dd"));
			}
		} catch (IllegalAccessException e) {
			LOGGER.error("EmailMessageResponseVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		} catch (InvocationTargetException e) {
			LOGGER.error("EmailMessageResponseVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
		EmailServerResponseVo emailServerResponseVo =emailServerService.findByShopId(emailServerConfiguration.getShopId("shopId"));
		emailMessageResponseVo.setEmailServerResponseVo(emailServerResponseVo);
		TaskQueue.addQueue(emailMessageResponseVo);
		return new PrimaryIdVo(id);
	}

	/**
	 * 批量发送邮件
	 * 
	 * @param emailMessageRequestVos
	 * @return
	 */
	@Override
	public int sendEmailMessageList(List<EmailMessageRequestVo> emailMessageRequestVos) {
		List<EmailMessage> emailMessages = new ArrayList<EmailMessage>();
		try {
			for (EmailMessageRequestVo emailMessageRequestVo : emailMessageRequestVos) {
				EmailMessage emailMessage = new EmailMessage();
				DateConverter dateConverter = new DateConverter();
				dateConverter.setTimeZone(TimeZoneUtil.getDefaultTimeZone());
				dateConverter.setPatterns(new String[] { "yyyy-MM-dd" });
				ConvertUtils.register(dateConverter, Date.class);
				BeanUtils.copyProperties(emailMessage, emailMessageRequestVo);
				emailMessages.add(emailMessage);
			}
		} catch (IllegalAccessException e) {
			LOGGER.error("EmailMessageRequestVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		} catch (InvocationTargetException e) {
			LOGGER.error("EmailMessageRequestVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}

		return 0;
	}


	/**
	 * 删除邮件
	 * 
	 * @param id
	 */
	@Override
	public void deleteEmailMessage(String id) {
		try {
			emailMessageMapper.deleteEmailMessageById(id);
		} catch (Exception e) {
			LOGGER.error("删除邮件信息时报错", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
	}


	/**
	 * 更新EmailMessage
	 * 
	 * @param size
	 *            条数
	 * @return locked
	 */
	@Override
	public String lockEmailMessage(int size) {
		String uuid = StringUtil.createUUID();
		try {
			emailMessageMapperExt.lockEmailMessage(uuid, size);
			return uuid;
		} catch (Exception e) {
			LOGGER.error("更新邮件信息时报错", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
	}

	/**
	 * 根据locked查询EmailMessage
	 * 
	 * @param uuid
	 *            locked
	 * @return 邮件列表
	 */
	@Override
	public List<EmailMessageResponseVo> findByLocked(String uuid) {
		List<EmailMessage> list = new ArrayList<EmailMessage>();
		try {
			list = emailMessageMapperExt.findByLocked(uuid);
		} catch (Exception e) {
			LOGGER.error("查询邮件信息时报错", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
		List<EmailMessageResponseVo> emailMessageResponseVos = new ArrayList<EmailMessageResponseVo>();
		if (list.size() > 0) {
			try {
				for (EmailMessage emailMessage : list) {
					EmailMessageResponseVo emailMessageResponseVo = new EmailMessageResponseVo();
					DateConverter dateConverter = new DateConverter();
					dateConverter.setTimeZone(TimeZoneUtil.getDefaultTimeZone());
					dateConverter.setPatterns(new String[] { "yyyy-MM-dd" });
					ConvertUtils.register(dateConverter, Date.class);
					BeanUtils.copyProperties(emailMessageResponseVo, emailMessage);
					if(StringUtils.isNotBlank(emailMessageResponseVo.getLockedTime())){
						emailMessageResponseVo.setLockedTime(DateUtil.date2String(emailMessage.getLockedTime(), "yyyy-MM-dd"));
					}
					if(StringUtils.isNotBlank(emailMessageResponseVo.getLastFireOn())){
						emailMessageResponseVo.setLastFireOn(DateUtil.date2String(emailMessage.getLastFireOn(), "yyyy-MM-dd"));
					}
					emailMessageResponseVos.add(emailMessageResponseVo);
				}
				return emailMessageResponseVos;
			} catch (IllegalAccessException e) {
				LOGGER.error("EmailMessageResponseVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
				throw new UserException(UserExceptionConstants.MAINTAINING, e);
			} catch (InvocationTargetException e) {
				LOGGER.error("EmailMessageResponseVo对象和EmailMessage对象在拷贝属性值的时候，抛出异常信息", e);
				throw new UserException(UserExceptionConstants.MAINTAINING, e);
			}
		}
		return null;
	}

	/**
	 * 解锁EmailMessage
	 * 
	 * @param id
	 *            EmailMessage的id
	 */
	@Override
	public void unlockEmailMessage(String id) {
		try {
			emailMessageMapperExt.unlockEmailMessage(id);
		} catch (Exception e) {
			LOGGER.error("更新邮件信息时报错", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
	}

	@Override
	public void unlockEmailMessageBylockTime(long lockTime) {
		try {
			emailMessageMapperExt.unlockEmailMessageLockTime(lockTime);
			LOGGER.debug("将加锁时间过长的数据进行解锁{}"+System.currentTimeMillis());
		} catch (Exception e) {
			LOGGER.error("将加锁时间过长的数据进行解锁时报错", e);
			throw new UserException(UserExceptionConstants.MAINTAINING, e);
		}
	}

}
